package controllers.interceptors

import com.jfinal.core.Controller
import com.jfinal.validate.Validator
import base.Message
import base.State
import common.permission.Permission
import common.permission.PermissionManager
import controllers.UserController
import models.UserM
import utils.SafeUtil

class UserTokenCheckValidator: Validator(){

    companion object{
        val TAG = UserTokenCheckValidator::class.simpleName!!
        fun getUserId(c: Controller): Int{
           return c.getAttr<Int>(UserController.PARA_USER_ID)
        }
    }

    override fun validate(c: Controller) {
        val token = c.getHeader(UserController.PARA_TOKEN)
       // println("Token: $token")
        if (token == null || token.isEmpty()){
          //  LogUtil.i(TAG, "token is null")
            addError(UserController.PARA_TOKEN, State.ERROR_USER_TOKEN_UNTRUSTWORTHY)
            return
        }
        val tmp = token.split("%")
        val userId = tmp[0]
        val user = UserM.AGENT.findById(userId)
        if (user == null){
            addError(UserController.PARA_TOKEN, State.ERROR_USER_TOKEN_UNTRUSTWORTHY)
            return
        }
        val pwd = user.get<String>(UserM.PASSWORD)
        if (!SafeUtil.checkToken(token,pwd)){
            addError(UserController.PARA_TOKEN, State.ERROR_USER_TOKEN_UNTRUSTWORTHY)
            return
        }
        val validTime = tmp[1].toLong()
        if (validTime <= System.currentTimeMillis()
                //如果登录权限被限制, Token失效
                || !PermissionManager.checkPermission(user.getInt(UserM.STATE), Permission.LOGIN)){
            addError(UserController.PARA_TOKEN, State.ERROR_USER_TOKEN_EXPIRED)
            return
        }
        c.setAttr(UserController.PARA_USER_ID, userId.toInt())
    }

    override fun handleError(c: Controller) {
        val error = c.getAttr<String>(UserController.PARA_TOKEN)
        val message = Message(State.STATE_FAIL, data = State.getEorrorStr(error))
        c.renderJson(message)
    }

}